import time

import uvicorn
from fastapi import FastAPI
from fastapi.security import OAuth2PasswordBearer
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.middleware.cors import CORSMiddleware
import os
from starlette.responses import JSONResponse
from starlette.staticfiles import StaticFiles
from config.config import settings, cache
from .core import Router
from .core.apscheduler import lifespan
from .core.exceptions import register_exception

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")

fastApi = FastAPI()


def get_application():
    _app = FastAPI(title=os.getenv('PROJECT_NAME'), lifespan=lifespan)
    register_exception(_app)
    _app.include_router(Router.router, prefix='/api')
    return _app


class ProcessHeadersMiddleware(BaseHTTPMiddleware):
    async def dispatch(self, request, call_next):
        try:
            headers = dict(request.headers)
            # 获取请求头
            lan = headers.get('lan')
            province = headers.get('province')
            region = headers.get('region')
            city = headers.get('city')
            # 这里可以假设 cache 是一个全局变量或通过依赖注入传入
            if lan:
                cache.set('lan', lan)
            if province:
                cache.set('province', province)
            else:
                cache.delete('province')
            if region:
                cache.set('region', region)
            else:
                cache.delete('region')
            if city:
                cache.set('city', city)
            else:
                cache.delete('city')
            # 继续调用下一个中间件或视图
            response = await call_next(request)
            return response
        except Exception as exc:
            # 这里可以根据异常类型做不同的处理
            # 例如，只捕获特定类型的异常，或根据状态码来判断
            return JSONResponse(
                content={
                    "code": 500,
                    "message": str(exc),
                    "data": None,
                },
                status_code=500,
                headers={"Content-Type": "application/json"},
            )


app = get_application()

origins = [
    "http://localhost",
    "http://localhost:8000",
    "http://localhost:10181",
    "http://localhost:10182",
]
app.add_middleware(ProcessHeadersMiddleware)
app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

if __name__ == "__main__":
    uvicorn.run(
        app='app.main:app',
        host="0.0.0.0",
        port=10182,
        reload=True,
        log_level="debug",
        lifespan="on",
    )

app.mount("/storage", StaticFiles(directory=settings.STATIC_DIR), name="storage")
